package com.keta.foundation.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.GeneratorStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.keta.foundation.entity.Module;
import com.keta.foundation.entity.Permission;
import com.keta.foundation.entity.Role;
import com.keta.foundation.log.Log;
import com.keta.foundation.log.LogUtil;
import com.keta.foundation.service.ModuleService;
import com.keta.foundation.shiro.ShiroUser;

/*
 * 系统首页控制器
 */
@Controller
public class IndexController {

	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

	private static final String INDEX_PAGE = "index/index";

	@Autowired
	private ModuleService moduleService;

	/*
	 * 系统首页
	 */
	@Log(message = "{0}用户登录了系统")
	@RequiresUser
	@RequestMapping("/index")
	public String index(Model model,HttpServletRequest request) {
		
		String path = request.getContextPath();

		ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List moduleList = moduleService.getByParentId(ModuleService.RootModuleId);

		Date now = new Date();
		int hours = now.getHours();

		// 根据不同时间，显示不同的欢迎语
		String welcome = "";
		if (hours >= 5 && hours < 12) {
			welcome = "上午好,";
		} else if (hours >= 12 && hours < 13) {
			welcome = "中午好,";
		} else if (hours >= 13 && hours < 18) {
			welcome = "下午好,";
		} else {
			welcome = "晚上好,";
		}
		
		
		Subject subject =SecurityUtils.getSubject();
		
		moduleList = check(moduleList,subject);
		
		model.addAttribute("menuModule", moduleList);
		model.addAttribute("welcome", welcome + shiroUser.getUser().getRealname());
		LogUtil.putArgs(new Object[] { shiroUser.getUser().getUsername() });

		logger.info(shiroUser.getUser().getUsername() + "用户登录了系统");

		return INDEX_PAGE;
	}
	
	/**
	 检查每个模块是否拥有权限
	 */
	private List<Module> check(List<Module> moduleList,Subject subject){
		
		List<Module> hasPermissionModules = new ArrayList<Module>();
		for(Module module : moduleList){
			String permissionStr = module.getSn() + ":" + Permission.PERMISSION_SHOW;
			System.out.println(permissionStr);
			if(subject.isPermitted(permissionStr)){
				List<Module> children = check(module.getChildren(),subject);
				module.setChildren(children);
				hasPermissionModules.add(module);
			}
		}
		
		return hasPermissionModules;
	}
}
